package com.ssm.controller;

import com.ssm.entity.Student;

import com.ssm.service.StudentService;
import com.sun.deploy.net.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * Created by Lenovo on 2019-4-21.
 */
@Controller
@RequestMapping("/Student")
@SessionAttributes("student")
public class StudentController {
        @Autowired
        private StudentService studentServiceImpl;
       @RequestMapping("list.do")
       public String list(Model model){
           //调用studentServiceImpl的list方法，从数据库取数据
           List<Student> students=studentServiceImpl.list();
          //通过model对象带出students数据，到listStudent.jsp页面
           model.addAttribute("students",students);
        return "listStudents";
    }
    @RequestMapping(value = "toAdd.do")
    public String toAdd(){
          return "addStudent";
    }

    @RequestMapping(value = "add.do",method = RequestMethod.POST)

    //@Validated后跟个JavaBean，紧跟其后的参数必定是BindingResult
    public String add(@RequestParam(value = "file")MultipartFile file, @Validated  Student student, BindingResult bindingResult, Model model) throws IOException {
        if (bindingResult.hasErrors()) {
            List<ObjectError> errors=bindingResult.getAllErrors();
            for (ObjectError objectError:errors){
                System.out.println(objectError);
            }
             return "addStudent";

        } else {
            uploadFile(file);
            student.setImage(file.getOriginalFilename());
           // 添加记录
            studentServiceImpl.insert(student);
            return "redirect:list.do";
        }
    }
    private void uploadFile(MultipartFile image) throws IOException {
        if(image!=null){

            File imageFile = new File(image.getOriginalFilename());// 上传后的文件保存目录及名字
            image.transferTo(imageFile);// 将上传文件保存到相应位置
        }
    }

}
